<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:insert="common/header :: head"></head>
<style>
    .grid-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, 450px); /* 自动适应宽度，每列固定 600px */
        gap: 10px; /* 设置间距，可根据需要调整 */
    }
    .row-red {
        background-color: red !important;
        color: black;
    }
    .row-light-red{
        background-color: lightcoral !important;
        color: black;
    }

    .row-pink{
        background-color: lightpink !important;
        color: black;
    }

</style>
<body>
<div id="app">
    <div style="width: 98%;margin: 0 auto;margin-bottom: 10px;">
        <el-select  v-model="term"  filterable size="small" placeholder="请选择学年"  clearable @change="changeTerm" >
            <el-option v-for="cls in terms " :key="cls" :label="cls" :value="cls"></el-option>
        </el-select>
        <el-select v-model="selectMajor"   filterable size="small" placeholder="请选择专业" @change="selectClass" clearable>
            <el-option v-for="major in selectMajors" :key="major" :label="major" :value="major"></el-option>
        </el-select>
        <el-select  v-model="yearnumber"  filterable size="small" placeholder="请选择年级" @change="selectClass" clearable>
            <el-option v-for="cls in selectyearnumber" :key="cls" :label="cls" :value="cls"></el-option>
        </el-select>
        <el-select  v-model="classNumber"  filterable size="small" placeholder="请选择班级"  clearable >
            <el-option v-for="cls in classInfo " :key="cls" :label="cls" :value="cls"></el-option>
        </el-select>
        <el-button style="margin-left: 20px;" @click="clickEvent" size="small" type="primary">查 询</el-button>
    </div>

    <!--  老师工作量  -->
    <div style="width: 98%;margin: 0 auto;height: 350px;" id="teacher_total">
        <div style="width: 81%;padding-top: 8px;background: #ffffff;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);float: left;">
            <div id="container" style="height:350px;"></div>
        </div>
        <div style="width: 18%;margin-left: 1%;height: 350px;float: left;padding: 5px;">
            <el-row style="font-size: 15px;font-weight:600;padding: 10px 0;
            text-align: center;">
                <el-col >课时量排行</el-col>
            </el-row>
            <div v-for="(item,index) in Workload" style="width: 100%;height: 50px;background: #ffffff;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            font-size: 13px;text-align: center;margin: 10px 0;padding-top: 5px;">
                <el-row style="margin-bottom: 8px;">
                    <el-col :span="2">{{index+1}}</el-col>
                    <el-col :span="16">{{item.teacherName}}</el-col>
                </el-row>
                <el-row style="color:#BABABA;">
                    <el-col :offset="2" :span="6">{{item.courses}}(节)</el-col>
                    <el-col :span="14" style="text-align: right;">{{item.Total_number}}个班/共{{item.teaching_staff}}人</el-col>
                </el-row>
            </div>
        </div>
    </div>

    <!--  班级考勤信息  -->
    <div style="width: 98%;margin: 0 auto;height: 350px;margin-top: 2%;margin-bottom: 2%;" id="student_total">
        <div style="width: 100%;padding-top:8px;background: #ffffff;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
            <div id="student_container" style="height:350px;"></div>
        </div>
    </div>
    <div style="display: none" id="app2">
        <span style="font-size: 20px;font-style: italic;font-weight: 600">学生考勤详细</span>
<!--       @selection-change="handleSelectionChange"-->
    <el-table :data="tableData.data"  v-loading="loading" border style="width: 100%" :row-class-name="rowStyle">
        <el-table-column prop="nickname" label="辅导员"></el-table-column>
        <el-table-column prop="stuid" label="学号"></el-table-column>
        <el-table-column prop="sname" label="姓名"></el-table-column>
        <el-table-column prop="arrived" label="已到"></el-table-column>
        <el-table-column prop="leave_ask" label="请假"></el-table-column>
        <el-table-column prop="leave_early" label="早退"></el-table-column>
        <el-table-column prop="be_late" label="迟到"></el-table-column>
        <el-table-column prop="absenteeism" label="旷课"></el-table-column>
<!--        <el-table-column prop="final_score"  label="分数"></el-table-column>-->
        <el-table-column prop="final_score" label="分数">
        </el-table-column>
    </el-table>

    <div style="background-color: white; padding: 10px 0;text-align: right">
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="pageNum"
                :page-sizes="pageSizes"
                :page-size.sync="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                background
                :total="total">
        </el-pagination>
    </div>

    </div>
</div>
</body>
<script type="text/javascript" th:src="@{/js/echarts.min.js}"></script>
<script type="text/javascript">
    var v = new Vue({
        el: "#app",
        data: {
            //x轴数据
            Xdata: [],
            //y轴数据
            Ydata: [],
            //专业
            selectMajors:[],
            //年份
            selectyearnumber:[],
            //查出来的班级
            classInfo:[],
            //选中的专业
            selectMajor:"",
            //选中的年份
            yearnumber:"",
            //选中的班级
            classNumber:"",
            //学年
            terms:[],
            //选中的学年
            term:"",
            //一学年
            dataYear:[],
            //上学期
            dataSemester1:[],
            //下学期
            dataSemester2:[],
            //总条数
            total: 0,
            // 学生数据
            tableData: [],
            // 分页信息
            pageNum: 1,
            pageSize: 10,
            pageSizes: [10, 20, 30, 40],
            loading: false,
            loadingStuInfo:false,//上传加载效果
            loadingStuInfoText:'拼命处理中请稍后',
            //直接查一年的总数据
            scheduleByYear:[],
            //直接查上半年的数据
            scheduleByUpYear:[],
            //直接查下半年的数据
            scheduleByDownYear:[],
            //今天的时间对应的学期
            nowTerm:"",
            //分数占比
            scoreproportion:[],
            //不合格的人数
            failPeople:[],
            classinfo:[],
            //课时量
            Workload:[],
            //问题班级
            questions:[]
        },
        async mounted() {
            try {
                await this.queryTime(); // 首先执行queryTime
                await this.Workload_ranking();
                await this.drawEractsBytear(); // 接着执行drawEractsBytear
                // 使用$nextTick确保下面的操作在DOM更新后执行
                this.$nextTick(() => {
                    this.drawEcharts();
                    this.drawEcharts1();
                });
            } catch (error) {
                console.error("Error occurred while fetching data:", error);
            }
        },
        created() {
            //查有哪些专业
            this.queryMname();
            //查年份
            this.queryYearNumber();
            //查班级
            this.selectClass();
            //查学期
            this.queryTerm();
        },
        methods: {
            //查出分数不及格的学生
            selectScore(){
                axios.get("../api/user/queryfail").then(res=>{
                    this.failPeople=res.data.data
                    // 提取所有的key值，存储到一个数组中
                    var allKeys = this.failPeople.map(item => Object.keys(item)[0]);
                    // 使用Set去重
                    var uniqueKeys = new Set(allKeys);
                    // 将Set转换为数组
                    var uniqueKeysArray = Array.from(uniqueKeys);
                    // 输出去重后的key值列表
                    // 初始化一个空对象，用于存储key出现的次数
                    var keyCounts = {};
                    // 遍历去重后的key值集合，计算每个key在原数据中出现的次数
                    uniqueKeys.forEach(key => {
                        var count = allKeys.filter(item => item === key).length;
                        keyCounts[key] = count;
                    });
                    // 输出每个key及其对应的次数
                    this.classinfo=keyCounts;
                })
            },
            //行内颜色随着分数变化
            rowStyle({row}) {
                if (row.final_score <= 20) {
                    return 'row-red';
                } else if (row.final_score <= 35) {
                    return 'row-light-red';
                } else if (row.final_score <= 40) {
                    return 'row-pink';
                } else {
                    return '';
                }
            },
            //监听变化
            selectClass(){
                this.classNumber=""
                axios.get("../selectClass",{
                   params:{
                        mname:this.selectMajor,
                        year:this.yearnumber
                    }
                }).then(res=>{
                    this.classInfo=res.data.data
                })
            },
            //监听学年变化
            changeTerm(){
                if (this.term==""){
                    this.queryTime();
                }else {
                    this.nowTerm=this.term
                }
            },
            //直接查询一年的
            drawEractsBytear(){
                  // 返回axios.get的Promise对象
                  return axios.get("../api/user/selectByteaYear", {
                      params: {
                          school_year: this.nowTerm,
                          mname:this.selectMajor,
                          cname:this.classNumber,
                          yearnumber:this.yearnumber
                      }
                  })
                      .then(res => {
                          this.scheduleByYear = res.data.data;
                      })
                      .then(() => {
                          // 这里可以添加其他的异步请求
                          return axios.get("../api/user/selectByteaUpYear", {
                              params: {
                                  school_year: this.nowTerm,
                                  mname:this.selectMajor,
                                  cname:this.classNumber,
                                  yearnumber:this.yearnumber
                              }
                          });
                      })
                      .then(res => {
                          this.scheduleByUpYear = res.data.data;
                      })
                      .then(() => {
                          // 这里可以添加其他的异步请求
                          return axios.get("../api/user/selectByteaDownYear", {
                              params: {
                                  school_year: this.nowTerm,
                                  mname:this.selectMajor,
                                  cname:this.classNumber,
                                  yearnumber:this.yearnumber
                              }
                          });
                      })
                      .then(res => {
                          this.scheduleByDownYear = res.data.data;
                      })
                      .then(()=>{
                          return axios.get("../api/user/query_question_class")
                              .then(res=>{
                              this.questions=res.data.data
                          })
                      })
                      .catch(error => {
                          console.error("Error occurred while fetching data:", error);
                          throw error;
                      });
            },
            //查询学生考勤
            //查询考勤
            queryTeaDataTable(){
                var elementById = document.getElementById("app2");
                var dom1 = document.getElementById('student_total');
                var elementById1 = document.getElementById('teacher_total');
                // document.getElementById('pet').innerHTML = '';
                if (this.classNumber==""){
                    dom1.style.display="block"
                    elementById1.style.display="block"
                    elementById.style.display="none"
                    return ;
                }
                dom1.style.display="none"
                elementById1.style.display="none"
                elementById.style.display="block"
                axios.get("../student/selectBystuInfoSum",{
                    params:{
                        pageNum:this.pageNum,
                        pageSize: this.pageSize,
                        cname:this.classNumber
                    }
                }).then(res=>{
                    this.tableData=res.data.data
                    this.total=this.tableData.total
                })
            },
            //点击查询事件
            async clickEvent(){
                await this.drawEractsBytear();
                await this.drawEcharts();
                this.Workload_ranking();
                this.queryTeaDataTable();
                this.$message.success("查询成功");
                // await this.selectproportion()
            },
            //分页器变化执行
            handleSizeChange(){
                this.queryTeaDataTable();
            },
            //分页器变化执行
            handleCurrentChange(){
                this.queryTeaDataTable();
            },
            //查专业
            queryMname(){
                axios.get("../queryMname").then(res=>{
                    this.selectMajors=res.data.data
                })
            },
            //查年份
            queryYearNumber(){
                axios.get("../classInfo/queryYearnumber").then(res=>{
                    this.selectyearnumber=res.data.data
                })
            },
            //查学期
            queryTerm(){
                axios.get("../queryTerm").then(res=>{
                    this.terms=res.data.data
                })
            },
            //查今天在哪个学期                  上线再用
            queryTime(){
                var currentDate = new Date();
                // 获取当前年份
                var currentYear = currentDate.getFullYear();
                // 获取当前月份
                var currentMonth = currentDate.getMonth() + 1;
                // 获取当前日期（天）
                var currentDay = currentDate.getDate();
                // 格式化当前日期
                let nowdays = currentYear + '-' + this.addZero(currentMonth) + '-' + this.addZero(currentDay);
                return  axios.get("../api/user/queryNowdays",{
                    params:{
                        nowdays:nowdays
                    }
                }).then(res=>{
                    this.nowTerm=res.data.msg
                })
            },
            // 添加补0函数
            addZero(num) {
                return num < 10 ? '0' + num : num;
            },
            drawEcharts(){
                let data = [];
                let teacherSet = new Set([...this.scheduleByYear.map(item => item.nickname), ...this.scheduleByUpYear.map(item => item.nickname), ...this.scheduleByDownYear.map(item => item.nickname)]);
                teacherSet.forEach(teacherName => {
                    let countYear = this.scheduleByYear.find(item => item.nickname === teacherName)?.total || 0;
                    let countSemester1 = this.scheduleByUpYear.find(item => item.nickname === teacherName)?.total || 0;
                    let countSemester2 = this.scheduleByDownYear.find(item => item.nickname === teacherName)?.total || 0;
                    data.push({
                        product: teacherName,
                        countSemester1: countSemester1,
                        countSemester2: countSemester2,
                        countYear: countYear
                    });
                });
                const productArray = data.map(item => item.product);
                const countSemester1Array = data.map(item => item.countSemester1);
                const countSemester2Array = data.map(item => item.countSemester2);
                const countYearArray = data.map(item => item.countYear);

                var dom = document.getElementById('container');
                var myChart = echarts.init(dom, null, {
                    renderer: 'canvas',
                    useDirtyRect: false
                });
                var option = {
                    title: {text: '教师工作量'},
                    tooltip: {trigger: 'axis',axisPointer: {type: 'cross',label: { backgroundColor: '#6a7985'}}},
                    legend: {data: [ '学年','上学期', '下学期']},
                    grid: {left: '3%',right: '4%',bottom: '3%',containLabel: true},
                    xAxis: [
                        { type: 'category',boundaryGap: false,
                            data: productArray
                        }
                    ],
                    yAxis: [{type: 'value'}],
                    series: [
                        {
                            name: '上学期',
                            type: 'line',
                            stack: 'Total',
                            areaStyle: {},
                            emphasis: {
                                focus: 'series'
                            },
                            data: countSemester1Array
                        },
                        {
                            name: '下学期',
                            type: 'line',
                            stack: 'Total',
                            areaStyle: {},
                            emphasis: {
                                focus: 'series'
                            },
                            data: countSemester2Array
                        },
                        {
                            name: '学年',
                            type: 'line',
                            stack: 'Total',
                            areaStyle: {},
                            emphasis: {
                                focus: 'series'
                            },
                            data: countYearArray
                        }
                    ]
                };
                if (option && typeof option === 'object') {
                    myChart.setOption(option);
                }
                window.addEventListener('resize', myChart.resize);
            },
            //画出问题班级的柱状图
            drawEcharts1(){
                var dom1 = document.getElementById('student_container');
                var myChart1 = echarts.init(dom1, null, {renderer: 'canvas', useDirtyRect: false});
                var chartData = [];
                var backendData=this.questions
                for (var i = 0; i < backendData.length; i++) {
                    var item = backendData[i];
                    chartData.push([item.cname, item.attendance_count, item.late_leave_count]);
                }
                var option1 = {
                    title: {text: '前20名问题班级'},
                    legend: {},
                    tooltip: {},
                    dataset: {
                        source: [
                            ['product', '考勤(总次数)', '旷课/迟到/早退(次课)'],
                            ...chartData
                        ]
                    },
                    grid: {x: 20, x2: 20, y:20, y2:20, left:60, right:60, top:40, bottom:40},
                    xAxis: {type: 'category'},
                    yAxis: {},
                    series: [{type: 'bar'},{type: 'bar'}]
                };
                if (option1 && typeof option1 === 'object') {
                    myChart1.setOption(option1);
                }
                window.addEventListener('resize', myChart1.resize);
            },
            //课时量排名
            Workload_ranking(){
                axios.get("../api/user/Workload_ranking",{
                    params:{
                        school_year: this.nowTerm,
                        mname:this.selectMajor
                    }
                }).then(res=>{
                this.Workload=res.data.data
                })
            }
        },
        computed: {
            getTableData() {
                return function (classinfo) {
                    // 将classinfo对象转换成数组
                    const tableData = Object.keys(classinfo).map((className) => ({
                        class: className,
                        count: classinfo[className]
                    }));
                    // 根据count属性对tableData进行升序排序
                    tableData.sort((a, b) => b.count - a.count );
                    return tableData;
                };
            }
        }
    });






</script>
</html>